//
//  WmcTeamExampleView.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/29.
//

import UIKit
import Kingfisher

class WmcTeamExampleView: WmcTeamCloudEmptyView {
    let cell_width = (Wmc_screenWidth - 82 - 12) / 3.0

    var model: WmcMediaPhotoModel?

    override func makeUI() {
        super.makeUI()

        imgView.isHidden = true
        noteLabel.isHidden = true

        addSubview(avatarView)
        addSubview(nameLabel)
        addSubview(imageView)
        addSubview(imageViewButton)
        addSubview(locationView)
        addSubview(videoIconImageView)
        addSubview(titleLabel)

        avatarView.snp.makeConstraints { make in
            make.top.equalTo(30)
            make.left.equalTo(16)
            make.height.width.equalTo(40)
        }

        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(avatarView.snp.right).offset(8)
            make.centerY.equalTo(avatarView.snp.centerY)
        }

        imageView.snp.makeConstraints { make in
            make.top.equalTo(avatarView.snp.bottom).offset(8)
            make.left.equalTo(nameLabel.snp.left)
            make.width.height.equalTo(cell_width)
        }

        locationView.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom).offset(8)
            make.left.equalTo(nameLabel.snp.left)
        }

        videoIconImageView.snp.makeConstraints { make in
            make.center.equalTo(imageView.snp.center)
            make.width.height.equalTo(28)
        }

        imageViewButton.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(imageView)
        }
    }

    override func bindViewAction() {
//        self.imageView.rx.tapGesture().bind {[weak self] _ in
//            guard let weakSelf = self else { return }
//            print("fuck it 2022")
//            weakSelf.playVideo()
//        }.disposed(by: rx.disposeBag)
//
        imageViewButton.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            print("fuck you")
            weakSelf.playVideo()
        }.disposed(by: rx.disposeBag)

        locationView.button.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.gotoLocatingMap()
        }.disposed(by: rx.disposeBag)
    }

    func bindModel(_ model: WmcMediaPhotoModel) {
        self.model = model

        if model.loadStatus == .loadFailure {
            imageView.image = "photo_load_failure".wmc_image
            return
        }

        var params = ""

        if model.resourceType == 0 {
            params = "x-oss-process=image/resize,h_200,m_lfit"
            videoIconImageView.isHidden = true
        } else if model.resourceType == 1 {
            params = "x-oss-process=video/snapshot,t_7000,ar_auto,f_jpg,m_fast"
            videoIconImageView.isHidden = false
        }

        var url = "\(model.url)"
        var symbol = "?"
        if url.contains(symbol) {
            symbol = "&"
        }
        url.append(contentsOf: "\(symbol)\(params)")

        if let imgUrl = URL(string: url) {
            let urlParts = model.url.components(separatedBy: "?")
            var key = model.url
            if urlParts.count == 2 {
                key = urlParts[0]
            }
            key.append("/thumb")
            imageView.kf.setImage(with: .network(Kingfisher.ImageResource(downloadURL: imgUrl, cacheKey: key)), placeholder: "image_placeholder".wmc_image, completionHandler: { [weak self] r in
                guard let weakSelf = self else { return }
                switch r {
                case .success:
                    model.loadStatus = .loadsuccess
                case .failure:
                    model.loadStatus = .loadFailure
                    weakSelf.imageView.image = "photo_load_failure".wmc_image
                }
            })
        }

        titleLabel.text = model.takeTimeStr
    }

    func playVideo() {
        let browseVM = WmcMediaBrowseVM()
        browseVM.topLeftStyle = .close
        browseVM.albumType = .system
        browseVM.tooMenuList = []
        guard let model = model else {
            return
        }
        browseVM.mediaList = [getMediaItem(model: model)]
        browseVM.backStyle = .right // 从右侧返回出
        // browseVM.shareFriendsCircleMode = .custom
        // browseVM.shareWechatMode = .custom
        let vc = WmcNavigatorManager.push(.imageBrowse, style: .alpha, parms: browseVM)
        vc?.hidesBottomBarWhenPushed = true
    }

    func getMediaItem(model: WmcMediaPhotoModel) -> WmcMedia {
        let media = WmcVideo(url: model.url)
        return media
    }

    lazy var avatarView: WmcMemberAvatarView = {
        let view = WmcMemberAvatarView()
        return view
    }()

    private lazy var videoIconImageView: UIImageView = {
        let view = UIImageView(image: "player_play_center".wmc_image)
        view.isHidden = true
        return view
    }()

    func createGradientLayer() -> CAGradientLayer {
        let gradientLayer = CAGradientLayer()

        gradientLayer.colors = [
            "#000000".yp.cgColor(0.6),
            UIColor.clear.cgColor,
        ]

        gradientLayer.locations = [0, 1]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
        let width = (UIScreen.main.bounds.width - 38) / 3.0
        gradientLayer.frame = CGRect(x: 0, y: 0, width: width, height: 35)
        return gradientLayer
    }

    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.adjustsFontSizeToFitWidth = true
        return label
    }()

    lazy var nameLabel: UILabel = {
        let view = UILabel()
        view.textColor = UIColor.wmc_grayH2_323233
        view.font = 14.yp.uiFont(weight: .semibold)
        view.text = "张三"
        return view
    }()

    lazy var imageView: UIImageView = {
        let view = UIImageView()
        view.isUserInteractionEnabled = true
        return view
    }()

    lazy var imageViewButton: UIButton = {
        let view = UIButton()
        return view
    }()

    lazy var locationView: WmcTeamLocationView = {
        let view = WmcTeamLocationView()
        view.isUserInteractionEnabled = true
        view.location = "成都市武侯区.天府软件园"
        return view
    }()
}

extension WmcTeamExampleView {
    private func gotoLocatingMap() {
        let maps = WmcMapManager.canOpenMaps()

        if maps.isEmpty {
            let alert = WmcAlertView()
            alert.title = "温馨提示"
            alert.msg = "请先安装地图app"
            alert.style = .confirm(title: "确定")
            alert.show()
            return
        }

        let selectMapAlertView = WmcSelectMapAlertView()
        selectMapAlertView.maps = maps
        addSubview(selectMapAlertView)

        selectMapAlertView.clickClosure = { [weak self] map in
            guard let weakSelf = self else { return }
            if let lat = weakSelf.model?.lat, let lon = weakSelf.model?.lon {
                WmcMapManager.openMap(latitude: lat, longitute: lon, name: "成都市武侯区.天赋软件园", mapType: map)
                YPApp.CurrentVC?.dismiss(animated: true)
            }
        }

        let presentVC = WmcPresentVC(config: .init(
            style: .sheet(),
            contentView: selectMapAlertView,
            contentLayoutBlock: { make in
                let count = maps.count <= 2 ? 3 : maps.count
                let height = 44.wmc_autoVer + CGFloat(52 * count) + Wmc_safeAreaBottom
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(height)
            }
        ))
        presentVC.show()
    }
}
